package com.client;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.channels.SocketChannel;
import java.util.List;

import org.apache.log4j.Logger;

import com.common.utilities.ReceiveData;
import com.game.ClientGameAPI;

/**
 * User: wattsc5
 * <p/>
 * Date: 2/28/12
 */
public class ResponseHandler
{
	private static final Logger logger = Logger.getLogger(ResponseHandler.class);

	public ClientGameAPI api;

	public ResponseHandler(ClientGameAPI api)
	{
		this.api = api;
	}

	public synchronized boolean handleResponse(SocketChannel socket, byte[] data)
	{
		List<ReceiveData> receiveDataSet;
		try
		{
			receiveDataSet = ReceiveData.extractDataSets(data, socket);
		}
		catch (IOException ex)
		{
			logger.warn("Bad data - " + socket.socket().getInetAddress() + ":" + socket.socket().getPort() + " - " + ex);
			logger.trace("Received data from - " + socket.socket().getInetAddress() + ":" + socket.socket().getPort() + " - " + new String(data));
			return false;
		}

		try
		{
			for (ReceiveData receiveData : receiveDataSet)
			{
				logger.debug("Calling command from - " + socket.socket().getInetAddress() + ":" + socket.socket().getPort() + " - " + receiveData.getCommandName());
				logger.trace("Received data from - " + socket.socket().getInetAddress() + ":" + socket.socket().getPort() + " - " + receiveData.getOriginalData());
				Class.forName("com.game.ClientGameAPI").getMethod(receiveData.getCommandName(), ReceiveData.class).invoke(this.api, receiveData);
			}
		}
		catch (IllegalAccessException e)
		{
			logger.error(e);
			logger.error("Received data from - " + socket.socket().getInetAddress() + ":" + socket.socket().getPort() + " - " + new String(data));
			e.printStackTrace();
			return true;
		}
		catch (InvocationTargetException e)
		{
			logger.error(e);
			logger.error("Received data from - " + socket.socket().getInetAddress() + ":" + socket.socket().getPort() + " - " + new String(data));
			e.printStackTrace();
			return true;
		}
		catch (NoSuchMethodException e)
		{
			logger.error(e);
			logger.error("Received data from - " + socket.socket().getInetAddress() + ":" + socket.socket().getPort() + " - " + new String(data));
			e.printStackTrace();
			return true;
		}
		catch (ClassNotFoundException e)
		{
			logger.error(e);
			logger.error("Received data from - " + socket.socket().getInetAddress() + ":" + socket.socket().getPort() + " - " + new String(data));
			e.printStackTrace();
			return true;
		}

		return false;
	}
}
